#coding: utf-8


import sys
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)

import time
import pymongo
from topapi import *
from exceptions import Exception

def get_yesterday():
    yesterday = time.localtime(time.time() - 86400)
    yesterday = time.strftime('%Y-%m-%d', yesterday)
    begin_time = yesterday+' 00:00:00'
    end_time = yesterday+' 23:59:59'
    return (begin_time, end_time)


def get_increment_trades(inc_obj, u):
    page_no = 1
    page_size = 100
    r = []
    begin_time, end_time = get_yesterday()
    while True:
        inc_info = inc_obj.trades_get(u['top_session'], u['_id'], 
                start=begin_time, end=end_time, 
                page_no=page_no, page_size=page_size)
        total_results = inc_info['total_results']
        if total_results <=0:
            return r
        r.extend(inc_info['notify_trades']['notify_trade'])
        if len(r) >= total_results:
            return r
        page_no += 1

def test_get_increment_trades():
    user = {
            "_id" : "jasonwood旗舰店",
            "top_session" : "6100e25d9aeb7df743c097e22cf7416ea1a31280eb68b79354823861",
    }
    inc = Increment()
    r = get_increment_trades(inc, user)
    import json
    json.dump({'r':r, 'len':len(r)}, open('test_get_increment_trades.json', 'w'))
       

def get_trades_and_store2db(db, user):
    inc_obj = Increment()
    trades_inc = get_increment_trades(inc_obj, user)
    trade_obj = Trade()
    for ti in trades_inc:
        trade = trade_obj.get(user['top_session'], ti['tid'])
        trade = trade['trade']
        trade['_id'] = trade['tid']
        db.trades.save(trade)

def test_get_trades_and_store2db():
    m = pymongo.Connection('127.0.0.1:57324')
    db = m.test
    user = {
            "_id" : "jasonwood旗舰店",
            "top_session" : "6100e25d9aeb7df743c097e22cf7416ea1a31280eb68b79354823861",
    }
    get_trades_and_store2db(db, user)


def traverse_and_update_trades(db):
    skip = 0
    limit = 100
    while True:
        cur = db.user.find(fields = ['top_session', 'status'], timeout=False).skip(skip).limit(limit)
        if cur.count(True) <= 0:
            print 'traverse users finish!'
            break
        for u in cur:
            try:
                if u['status'] != 'normal':
                    print 'user error: %s, %s' %(u['_id'], u['status'])
                    continue
                get_trades_and_store2db(db, u)
            except Exception as e:
                print 'update trades for user fail: %s, %s' %(u['_id'].encode('utf8'), repr(e))
                continue
            print 'processed: %s' %(u['_id'].encode('utf8'))
        skip += limit
    


if __name__ == '__main__':
    m = pymongo.Connection('127.0.0.1:57324')
    db = m.taogold
    #test_get_increment_trades()
    #test_get_trades_and_store2db()
    traverse_and_update_trades(db)


